<template>
  <div class="wapper">
    <div class="box">
      <div class="content">
        <h2>登录</h2>
        <form @submit.prevent="handleLogin"> <!-- Form added here -->
          <div>
            <input type="text" placeholder="用户名" v-model="username" />
          </div>
          <div>
            <input type="password" placeholder="密码" v-model="password" />
          </div>
          <div>
            <input type="submit" value="登录" />
          </div>
        </form>
        <!-- 错误提示信息 -->
        <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
      </div>
      <a href="/forgot-password" class="btns">忘记密码</a>
      <a href="/register" class="btns register">注册</a>
    </div>
  </div>
</template>


<script>
import axios from "axios";
import "@/assets/css/home.css"; // 引入你的CSS样式

export default {
data() {
  return {
    username: "",
    password: "",
    errorMessage: "", // 用于存储错误信息
  };
},
methods: {
  async handleLogin() {
    this.errorMessage = "";

    // 检查用户名是否为空
    if (!this.username) {
      this.errorMessage = "请输入账号";
      return;
    }

    // 检查密码是否为空
    if (!this.password) {
      this.errorMessage = "请输入密码";
      return;
    }

    try {
      // 发送 POST 请求到后端登录 API
      const response = await axios.post("http://localhost:8000/api/login/", {
        username: this.username,
        password: this.password,
      });

      // 登录成功后保存登录状态
      localStorage.setItem("isLoggedIn", "true");

      // 登录成功后，重定向到首页
      this.$router.push("/index");

      // 可选：显示成功消息
      this.successMessage = response.data.message || "登录成功！";
    } catch (error) {
      // 错误处理
      this.errorMessage = error.response?.data?.error || "登录失败";
    }
  },
},
};
</script>

